package org.maurange.formation.licpro;

import java.util.ArrayList;

import org.json.JSONArray;
import org.maurange.formation.licpro.rest.InfoArretRestMethod;
import org.maurange.formation.licpro.rest.ListInfoArret;

import android.annotation.TargetApi;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class TempsAttenteActivity extends ListActivity{
	
	private static final String LOG_TAG = "TEMPS_ATTENTE";
	private CallWebServiceAsyncTask task;
	
	private InfoAdapter infoAdapter;
	
	private String codeLieu;
	
	
	@TargetApi(12)
	public void onCreate(Bundle savedInstanceState)  {
		super.onCreate(savedInstanceState);
		task = (CallWebServiceAsyncTask) getLastNonConfigurationInstance();
		infoAdapter = new InfoAdapter(this, new ListInfoArret());
		setListAdapter(infoAdapter);
		
		Bundle extras = getIntent().getExtras();
		codeLieu = extras.getString("code_lieu", "null");
	}
	
	public Object onRetainNonConfigurationInstance(){
    	task.detach();
    	return task;
    }
	
	protected void onResume() {
		super.onResume();
		
		if (task != null){
        	relaunchTask();
        }
        else{
	        //appel de l'asynctask
	        this.task = new CallWebServiceAsyncTask(this, infoAdapter);
	        Log.d(LOG_TAG, "codeLieu : " + codeLieu);
	        task.execute(codeLieu);
        }
	}
	
	private void relaunchTask() {
		task.detach();
		task.cancel(true);
    	task = new CallWebServiceAsyncTask(this, infoAdapter); 
    	task.execute(codeLieu);
	}
	
	protected void onPause() {
		super.onPause();
	}
	
	public void setData(JSONArray data){
		 Log.d("SETTING DATA", "data : " + "=>"+data.toString()+"<=");
	}
	
	static private class CallWebServiceAsyncTask extends AsyncTask<String, Void, ListInfoArret>{

		private InfoArretRestMethod rest;
		private TempsAttenteActivity activity;
		private  InfoAdapter adapter;
		
		public CallWebServiceAsyncTask(TempsAttenteActivity activity, InfoAdapter adapter){
			this.activity= activity;
			rest = new InfoArretRestMethod(activity); 
			this.adapter = adapter;
		}
		
		protected ListInfoArret doInBackground(String... codes) {
			return rest.getInfoArretRest(codes[0]);
		}
		
		protected void onPostExecute(ListInfoArret data){
			try{
				adapter.getListArret().clear();
			}catch (Exception e) {}
			adapter.getListArret().addAll(data);
			adapter.notifyDataSetChanged();
		}
		
		public void detach(){
			this.activity = null;
		}
		
		public void attach(TempsAttenteActivity a){
			this.activity = a;
		}
		
	}
}
